package com.qfedu.openapi.web.master.controller;

import com.qfedu.openapi.web.master.entity.User;
import com.qfedu.openapi.web.master.service.UserService;
import com.qfedu.openapi.web.master.vo.MessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;


    @RequestMapping("login")
    @ResponseBody
    // 登录
    public MessageVo login(String captcha, User user, HttpSession session){

        MessageVo messageVo = new MessageVo();

        // 从session中获取谷歌验证码的值
        String sessionCapchar = (String) session.getAttribute("captcha");

        // 首先校验验证码是否正确
        if(captcha == null || !captcha.equals(sessionCapchar)){
            // 验证码错误，直接返回登录失败
            messageVo.setCode("-2");
            messageVo.setMessage("验证码错误");
            return messageVo;
        }

        // 登录的业务逻辑
        if(userService.checkUser(user)){
            // 登录成功 ， 保存用户的登录状态 ，用户的信息放入session中
            session.setAttribute("user",user);

            messageVo.setCode("1"); // code 为1 代表登录成功
            messageVo.setMessage("登录成功");
            messageVo.setData(user);
            return messageVo;
        }else {
            messageVo.setCode("-1");
            messageVo.setMessage("用户名或密码错误");
            return messageVo;
        }
    }
}
